// pages/store/acti/userImg/userImg.js
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
import Dialog from '@vant/weapp/dialog/dialog';
var { generateUUID } = require('../../../utils/uuid');
var { getFileExtension } = require('../../../utils/file');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: getApp().globalData.CustomBar,
    scrollHeight: '100vh',
    userImg: {},
    show: false,
    actiTitleColumns: [],
    actiMap: [],
    showCardType: false,
    cardTypeColumns: [],
    cardTypeMap: new Map(),
    fileList: [],
  },
  getScrollHeight() {
    // 获取内容区域的高度
    wx.createSelectorQuery().selectViewport().scrollOffset((res) => {
      this.setData({ scrollHeight: res.scrollHeight + 'px' });
    }).exec()
  },
  queryActiList() {
    getApp().callContainer('/api/actiQuery/list', {}, (res) => {
      if (res.data.data.actiList != null) {
        const actiTitleColumns = [];
        const actiMap = new Map();
        for (const acti of res.data.data.actiList) {
          actiTitleColumns.push(acti.actiTitle);
          actiMap.set(acti.actiTitle, acti.actiId);
        }
        this.setData({ actiTitleColumns: actiTitleColumns, actiMap: actiMap });
      }
    })
  },
  onClearForm() {
    this.setData({
      userImg: {},
      fileList: [],
    })
  },
  onShowActiList() {
    this.setData({ show: true })
  },
  onClose() {
    this.setData({ show: false })
  },
  onConfirm(event) {
    this.setData({ show: false });
    this.setData({ 'userImg.actiTitle': event.detail.value });
    this.setData({ 'userImg.actiId': this.data.actiMap.get(event.detail.value) });
  },
  
  // 查询卡片类型列表
  qryCardTypeList() {
    getApp().callContainer('/api/store/card/list', {}, (res) => {
      if (res.data.data) {
        const cardTypeColumns = [];
        const cardTypeMap = new Map();
        for (const cardType of res.data.data.cardList) {
          cardTypeColumns.push(cardType.name);
          cardTypeMap.set(cardType.name, cardType.cardId);
        }
        this.setData({ cardTypeColumns: cardTypeColumns, cardTypeMap: cardTypeMap });
      }
    });
  },
  // 展示卡片类型选择器
  onShowCardType() {
    this.setData({ showCardType: true });
    this.qryCardTypeList();
  },
  // 确认选择卡片类型
  onConfirmCardType(event) {
    this.setData({ showCardType: false });
    this.setData({ 'userImg.cardName': event.detail.value });
    this.setData({ 'userImg.cardId': this.data.cardTypeMap.get(event.detail.value) });
  },
  // 关闭卡片类型选择器
  onCloseCardType() {
    this.setData({ showCardType: false });
  },
  // 文件选择后
  afterRead(event) {
    const fileList = event.detail.file;
    // 组装文件前缀
    for (const file of fileList) {
      const currDate = new Date().toLocaleDateString().replaceAll('/', '-');
      const filePath = 'acti_user_picture/' + currDate + '/';
      const fileName = generateUUID() + '.' + getFileExtension(file.url);
      file.fileName = filePath + fileName;
    }
    // 调用文件上传接口
    const uploadTasks = fileList.map((file) => getApp().uploadFilePromise(file.fileName, file.url));
    Promise.all(uploadTasks)
      .then(data => {
        if (data && data.length > 0) {
          for (const item of data) {
            this.data.fileList.push({ url: item.fileID });
          }
          Toast('上传成功');
          this.setData({ fileList: this.data.fileList });
          setTimeout(() => {
            this.getScrollHeight();
          }, 1000)
        }
      })
      .catch(e => {
        Toast('上传失败');
        console.log(e);
      });
  },
  // 删除图片
  deleteFile(event) {
    this.data.fileList.splice(event.detail.index, 1);
    this.setData({ fileList: this.data.fileList });
    this.getScrollHeight();
  },
  // 提交
  onClickToSubmit() {
    if (!this.data.userImg.actiId) {
      Toast('请选择活动！');
      return;
    }
    if (!this.data.userImg.cardId) {
      Toast('请选择卡片类型！');
      return;
    }
    if (!this.data.fileList || this.data.fileList.length == 0) {
      Toast('请上传图片！');
      return;
    }
    const imgUrlList = [];
    for (const file of this.data.fileList) {
      imgUrlList.push(file.url)
    }
    const param = {
      ...this.data.userImg,
      imgUrlList: imgUrlList.join(","),
    }
    getApp().callContainer('/api/acti/saveUserImg', param, (res) => {
      if (res.data.code == 0) {
        this.onClearForm();
        Notify({ type: 'success', message: '提交成功！', top: this.data.CustomBar });
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.queryActiList();
    this.qryCardTypeList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})